package com.jt.common.interceptor;

import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 框架设计时会有一些对象的定义和和这些对象的执行流程，类似一个执行链
 */
//拦截器对象 默认方法
interface HandlerInterceptor{
    default void before(){}
    default void after(){}
}
//处理器接口
interface Handler{
    void processed();//处理业务的方法
}
//定义一个执行链
class ExecutionChain{
    private List<HandlerInterceptor> interceptors = new CopyOnWriteArrayList<>();// 一些拦截器 线程安全
    private Handler handler;//处理器

    public ExecutionChain(List<HandlerInterceptor> interceptors, Handler handler) {
        this.interceptors.addAll(interceptors);
        this.handler = handler;
    }

    public void execute(){//负责执行业务方法
        for (int i = 0; i <interceptors.size(); i++) {
            interceptors.get(i).before();
        }
        handler.processed();
        for (int i = interceptors.size()-1; i >= 0; i--){
            interceptors.get(i).after();
        }
    }
}
public class FrameworkTests {
    public static void main(String[] args) {
        List<HandlerInterceptor> interceptors = new CopyOnWriteArrayList<>();
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public void before() {
                System.out.println("开始考试:" + LocalTime.now());
            }

            @Override
            public void after() {
                System.out.println("结束考试：" + LocalTime.now());
            }
        };
        interceptors.add(handlerInterceptor);
        Handler handler = new Handler() {
            @Override
            public void processed() {
                System.out.println("考试中。。。。");
            }
        };
        ExecutionChain chain = new ExecutionChain(interceptors,handler);//构建执行链对象
        chain.execute();
    }
}
